﻿using Microsoft.AspNetCore.Http;
using SXICE.Core.Configs;
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using SXICE.AdminAPI.Models;
using SXICE.AdminAPI.Utilities;

namespace SXICE.AdminAPI.Middlewares
{
    /// <summary>
    /// 验证中间件
    /// </summary>
    public class AuthorizeMiddleware
    {
        private readonly RequestDelegate next;
        private readonly JwtSettings jwtSettings;
        private const string AUTHORIZATION = "Authorization";

        public AuthorizeMiddleware(RequestDelegate next, JwtSettings jwtSettings)
        {
            this.next = next;
            this.jwtSettings = jwtSettings;
        }

        public async Task Invoke(HttpContext httpContext)
        {
            if (jwtSettings.AuthorizationType == AuthorizationTypeEnum.Token && httpContext.Request.Headers.ContainsKey(AUTHORIZATION)
                && JwtHelper.ValidateToken(httpContext.Request.Headers[AUTHORIZATION], jwtSettings) is DoctorClaimsPrincipal customer)
            {
                httpContext.User = customer;
                //如果验证过期时间并且开启自动颁发令牌
                if (jwtSettings.LifeTime > 0 && !string.IsNullOrWhiteSpace(jwtSettings.AutoReIssueTokenHeader))
                {
                    //添加响应头信息
                    httpContext.Response.Headers.Add("Access-Control-Expose-Headers", jwtSettings.AutoReIssueTokenHeader);
                    httpContext.Response.Headers.Add(jwtSettings.AutoReIssueTokenHeader, JwtHelper.GenerateToken(customer, jwtSettings));
                }
            }
            else if (jwtSettings.AuthorizationType == AuthorizationTypeEnum.Cookie && httpContext.Request.Cookies.ContainsKey(AUTHORIZATION)
                && JwtHelper.ValidateToken(httpContext.Request.Cookies[AUTHORIZATION], jwtSettings) is DoctorClaimsPrincipal customer1)
            {
                httpContext.User = customer1;
                //如果验证过期时间并且开启自动颁发令牌
                if (jwtSettings.LifeTime > 0)
                    httpContext.Response.Cookies.Append(AUTHORIZATION, JwtHelper.GenerateToken(customer1, jwtSettings),
                        new CookieOptions { HttpOnly = true });
            }
            await next(httpContext);
        }
    }

    public static class AuthorizeMiddlewareExtention
    {
        public static void UseAuthorizeMiddleware(this IApplicationBuilder application)
        {
            application.UseMiddleware<AuthorizeMiddleware>();
        }
    }
}
